#!/usr/bin/env python
#coding=utf-8

import os
import json
import yaml
from kubernetes import client
from core.logger import logger
from common.welab_k8s.k8s_utils import K8sUtils

class K8sNode(object):

    def __init__(self):
        self.apps_v1 = client.CoreV1Api()


    def list_node(self):
        try:
            resp = self.apps_v1.list_node()
        except Exception as e:
            logger.error(f"list node error=>{e}")
            return None

        return resp.items


    def get_k8s_node_info(self):
        """
        获取k8s的node节点信息
        """
        k8s_node_infos = []
        k8s_nodes = self.list_node()
        if not k8s_nodes:
            logger.error(f"get k8s node list error")
            return False

        for k8s_node in k8s_nodes:
            k8s_node_info = {
                "cpu_alloc": K8sUtils.cpu_unit_to_G(k8s_node.status.allocatable["cpu"]),
                "mem_alloc": K8sUtils.mem_unit_to_G(k8s_node.status.allocatable["memory"])
            }

            # 获取node的ip地址
            for addr in k8s_node.status.addresses:
                if addr.type == "InternalIP":
                    k8s_node_info["node_ip"] = addr.address
                    break
            else:
                k8s_node_info["node_ip"] = ""

            # 获取node的状态
            for condition in k8s_node.status.conditions:
                if condition.type == "Ready" and condition.status == "True":
                    k8s_node_info["status"] = "Ready"
                    break
            else:
                k8s_node_info["status"] = "NoReady"

            # 获取node的标签
            k8s_node_info["labels"] = k8s_node.metadata.labels

            k8s_node_infos.append(k8s_node_info)

        return k8s_node_infos